package com.puboot.component;

import com.fasterxml.jackson.databind.type.TypeFactory;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Collections;
import java.util.List;

/**
 * @author Leonidax
 * @date 2024/10/17 20:39
 * @description Json2ClassConvert
 */

public class Json2ClassConvert {
    public static <T> T json2Class(String json, Class<T> clazz) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.readValue(json, clazz);
        }catch (Exception e){
            return null;
        }
    }
    public static <T> String class2Json(T obj) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(obj);
        }catch (Exception e){
            return null;
        }
    }
    public static String list2Json(List<?> list) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(list);
        }catch (Exception e){
            return null;
        }
    }

    public static <T> List<?> json2List(String json, Class<?> elementClass) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.readValue(json, TypeFactory.defaultInstance().constructCollectionType(List.class, elementClass));
        } catch (Exception e) {
            e.printStackTrace();  // 记录错误信息，方便调试
            return Collections.emptyList();  // 返回空列表，避免null问题
        }
    }
}